from django.shortcuts import render
from rest_framework.views import APIView
from orders.models import OrderInfo
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from alipay import AliPay
from django.conf import settings
import os
from .models import Payment


# Create your views here.

class PatmentView(APIView):
    """
    生成支付链接
    """
    permission_classes = [IsAuthenticated]
    def get(self, request, order_id):
        # 获取当前用户的请求用户对象
        user = request.user
        # 检验订单的有效性
        try:
            order_model = OrderInfo.objects.get(order_id=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return Response({'message': '订单有误'}, status=status.HTTP_400_BAD_REQUEST)

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None, #默认回调url
            app_private_key_string=open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem')).read(),
            alipay_public_key_string=open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/alipay_public_key.pem')).read(),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order_model.total_amount),
            subject='商城%s' % order_id,
            return_url="http://127.0.0.1:8080/pay_success.html",
        )
        alipay_url = settings.ALIPAY_URL + '?' + order_string

        return Response({'alipay_url': alipay_url})


class PaymentStatusView(APIView):
    """修改订单状态 保存支付宝交易号"""

    def put(self, request):
        # 获取前端以查询字符串方式传入的数据
        queryDict = request.query_params
        # 将queryDict类型专转成字典 要将中间的sign 从里面移除 单独验证
        data = queryDict.dict()
        # sign这个数据从字典中移除
        sign = data.pop('sign')
        # 创建alipay支付宝对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=open(
                os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem')).read(),
            alipay_public_key_string=open(
                os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/alipay_public_key.pem')).read(),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 调用alipay sdk中的verify方法进行验证 支付结果是不是支付宝回传
        success = alipay.verify(data, sign)
        if success:
            # 取出美多商城订单编号 取出支付宝交易号
            order_id = data.get('out_trade_no') # 订单编号
            trade_no = data.get('trade_no') # 支付宝交易号
            # 把两个编号绑定到一起存储到mysql
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_no,
            )
            # 修改支付成功后的订单状态
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])

        else:
            return Response({'message': '非法请求'}, status=status.HTTP_403_FORBIDDEN)

        # 把支付宝交易号响应会前端
        return Response({'trade_id': trade_no})



